package game.leon.seawar.server;

import game.leon.engine.utils.LinkedNode;
import game.leon.seawar.server.handler.HandlerService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * User: bianpeng
 * Date: 11-12-27
 * 游戏消息处理
 * raw message的data中, 可能还会夹带一些数据, 需要注意
 */
@Component
public class MessageConsumer {
    private Logger logger = Logger.getLogger(getClass());
    @Autowired
    private HandlerService handlerService;
    private ExecutorService executorService = Executors.newSingleThreadExecutor();
    @PreDestroy
    public void destroy() {
        logger.info("message consumer going to shutdown");
        executorService.shutdown();
        logger.info("message consumer shutdown");
    }

    private void execute(final GameMessage gameMessage) {
        logger.info(String.format("[server] gameMessage=%d", gameMessage.getRawMessage().getMessage()));
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    handlerService.execute(gameMessage);
                } catch (IOException e) {
                    logger.error("[server] handle gameMessage failed", e);
                }
            }
        });
    }
    public void consume(LinkedNode<GameMessage> messageList) {
        while (messageList != null) {
            execute(messageList.getItem());
            messageList = messageList.getNext();
        }
    }
    //
    // 延时消息的处理
    //
    public void consumeDelay(LinkedNode<DelayMessage> node) {
        while (node != null) {
            execute(node.getItem());
            node = node.getNext();
        }
    }
    private void execute(final DelayMessage message) {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    handlerService.execute(message);
                } catch (IOException e) {
                    logger.error("[server] handle delay message failed", e);
                }
            }
        });
    }
}
